var umode="login",wmode="about",cusermode,cwemode,clip,flagkey,fllink,status=-1,lu=fok=fnok=null,mtime=Infinity,now=Mtime=0,rdt,ddlg,dalert,dalertm,dalertc,dwe,dyou,dflag,dumode,dwmode,duerrores,dwerrores,info,dimg,durlinfo,iurl,itag,iurltitle,iurldesc,iurlwithimage,ltw,lfb,lst,on,dpop,pops,lasts,cpop=10;
lut=islastajax=ispopajax=drd=force=lastlast=activePreview=false;
var urlimgloaded=0;
function s(){
    if(status>0)return;
    extra="";
    url=escape(iurl.val());
    tag=itag.val();
    if(tag!="")tag="&keyword="+escape(tag);
    if(status==0){
        title=iurltitle.val();
        if(title!="")extra="&title="+escape(title);
        desc=iurldesc.val();
        if(desc!="")extra+="&desc="+escape(desc);
        if(iurlwithimage.val()!=""&&limg>-1)extra="&image="+urlimgs[limg]
    }
    status=1;
    if(force){
        force=false;
        extra+="&title="+url
    }
    sinfo("Acortando dirección...","l");
    $.ajax({
        url:'yourls-api.php?url='+url+'&format=json&action=shorturl'+tag+extra,
        dataType:'json',
        success:function(o){
            if (o==null||o['status']!="success"){
                status=0;
                if(o!=null&&o['errorCode']=='404')r(); else sinfo(o['message'],"e");
                return
            }
            status=2;
            sinfo(o['message'],"i");
            su=o['shorturl'];
            itag.val(o['shorturl']);
            iurl.val(o['url']['url']);
            clip.setText(su);
            sc($("#input"),"done");
            lcp.attr("href",'#');
            ltw.attr("href",'http://twitter.com/intent/tweet?text='+su);
            lfb.attr("href",'http://www.facebook.com/share.php?u='+su);
            lst.attr("href",su+'+');
            rd()
        }
    });
}
function r(){
    dalrt("No hemos podido acceder a esa dirección. ¿Estás seguro que deseas acortarla?",function(){
        force=true;
        s()
        },function(){
        sinfo('','')
        })
    }
function sc(o,c){o.attr("class",c)}
function clear(){
    $("#input").removeClass("done");
    durlinfo.removeClass("selected");
    limg=-1;
    status=-1;
    iurl.val("http://");
    itag.val("");
    sinfo("","");
    ltw.removeAttr("href");
    lfb.removeAttr("href");
    lst.removeAttr("href");
    lcp.removeAttr("href");
    clip.setText("")
    }
function sinfo(m,t){
    info.html(m);
    sc(info,t)
    }
function chits(n){
    $("#l"+on).removeClass("selected");
    $("#d"+on).removeClass("selected");
    $("#l"+n).addClass("selected");
    $("#d"+n).addClass("selected");
    on=n
}
function id(o){
    return eval('typeof '+o)!='undefined'
}
function dh(){
    if(id('innerHeight')){
        if(document.body.clientHeight!=innerHeight)return document.body.clientHeight;
        return document.documentElement.clientHeight
    }
        return document.body.clientHeight
}
function ch(){
    if(id('innerHeight'))return innerHeight;
    if(id('document.documentElement.clientHeight'))return document.documentElement.clientHeight;
    return document.body.clientHeight
}
function st(){
    if(id('pageYOffset'))return pageYOffset;
    if(id('document.documentElement.scrollTop')) return document.documentElement.scrollTop;
    return document.body.scrollTop
}
function ws(){
    if(!lastlast && st()+ch()>dh()-400)ajaxl(-mtime)
}
function setImage(desp){
    dimg.removeClass("loading");
    if (desp==0) limg=0;
    else limg=(limg+desp+urlimgloaded) % urlimgloaded;
    $("#imgcnt").text((limg+1) + " de " + urlimgloaded);
    dimg.css("background-image","url(image.php?width=150&height=150&cropratio=1:1&image="+urlimgs[limg]+")");

}
function gval(v){
    if(v==null||v==undefined)return "";else return v;
}
function isempty(){
    if(this!=document.activeElement&&this.value=='')$(this).addClass("empty");else $(this).removeClass("empty");
}

function loadImage(index){
    urlimgloaded=index;
    if (index>=urlimgs.length)return;
    $("#imgcnt").text((limg+1) + " de " + index);
    $('<img/>').attr("src","image.php?width=150&height=150&cropratio=1:1&image="+urlimgs[index])
        .load(function(){if(index==0)setImage(0);loadImage(index+1);})
        .error(function(){urlimgs.splice(index,1);loadImage(index)});
}

var vurl = /(https?:\/\/)?(\w+:{0,1}\w*@)?(([^\s\.\/]+\.)+[^\s\.\/]{2,})(:[0-9]+)?(\/([\w#!:.?+=&%@!\-\/])*)?/;
function urlinfo(){
    lut=false;
    tu=trim(iurl.val());
    if(tu==lu||!vurl.test(tu))return;
    lu=tu;
    durlinfo.addClass("selected loading");
    $.ajax({
        url:'yourls-api.php?format=json&action=urlinfo&url='+lu,
        dataType:'json',
        success:function(d){
            status=0;
            iurltitle.val(gval(d.title));
            iurldesc.val(gval(d.desc));
            iurltitle.change();
            iurldesc.change();
            urlimgs=d.images;
            if(urlimgs==null||urlimgs.length==0)
                durlinfo.addClass("noimage");
            else {
                dimg.addClass("loading");
                loadImage(0);

//setimage(0);
            }
            durlinfo.removeClass("loading");
        }
    });
}
function i(){
    ih();
    document.body.onscroll=ws;
    window.onscroll=ws;
    dpop=$("#popl");
    dlast=$("#lastl");
    dimg=$("#uimg");
    durlinfo=$("#urlinfo");
    iurltitle=$("#urltitle");
    iurldesc=$("#urldesc");
    iurlwithimage=$("#withimage");
    limg=-1;
    iurltitle.bind("focus blur change keyup click", isempty);
    iurldesc.bind("focus blur change keyup click", isempty);
    lcp=$("#cp");
    ltw=$("#tw");
    lfb=$("#fb");
    lst=$("#st");
    iurl=$("#url");
    itag=$("#tag");
    if (activePreview) {
        iurl.bind("blur change keypress click", function(){
            if(status>0)return false;
            if(lut)clearTimeout(lut);
            lut=setTimeout(urlinfo,500);
            return true;
        });
        itag.bind("blur change keypress", function(){return status<=0});
    }
    iurl.val("http://");
    itag.val("");
    info=$("#info");
    clip=new ZeroClipboard.Client();
    clip.addEventListener('onComplete',function(){
        if(status<=0)return;
        if(clip.clipText=="")sinfo("No hay nada para copiar.","e");else sinfo("¡Dirección corta copiada!","i")
            });
    clip.glue('cp',"actions_container");
    clip.setHandCursor(true);
    setInterval("ajaxl(Mtime)",15000);
    setInterval("pop(Mtime)",60000);
    ajaxl(Mtime);
    pop(Mtime);
    rd();
}
function rd(){
    drd.addClass("repaint block");
    rdt=setTimeout(ndlg,10)
}
function ajaxl(t){
    if (islastajax)return;
    islastajax=true;
    $.ajax({
        dataType:'json',
        url:'yourls-api.php?format=json&action=last&limit=20&t='+t,
        success:function(tlast){
            islastajax=false;
            now=tlast['n'];
            if(tlast!=null){
                lasts=tlast['r'];
                ul(t>=0?0:-1);
                if(tlast['T']>=tlast['t']){
                    if(tlast['T']>Mtime)Mtime=tlast['T'];
                    if(tlast['t']<mtime)mtime=tlast['t']
                }else{
                    if(tlast['T']==-1){
                        lastlast=true;
                        $("#lloading").css("display","none");
                    }
                }
            }
        }
    });
}
function trim(str){
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
}
function vote(k,t){
    $.ajax({
        url:'yourls-api.php?format=json&action=vote&keyword='+k+'&type='+t,
        success:function(){
            $(".visitas.key"+k).removeClass("type"+(3-t));
            $(".visitas.key"+k).addClass("type"+t);
            pop()
        }
    });
}
function flag(k){
    if($(".visitas.key"+k).hasClass("typef"))return;
    dlg(dflag);
    flagkey=k
}
function flsend(){
    ff=$("#fflag").serialize();
    $.ajax({
        type:"POST",
        dataType:'json',
        data:ff,
        url:'yourls-api.php?format=json&action=vote&keyword='+flagkey,
        success:function(ret){
            if(ret!=null&&ret['errors']){
                dferrores.html("<ul><li>"+ret['errors'].join("</li><li>")+"</li></ul>");
                return
            }
            dferrores.html("");
            ndlg();
            freset("#fflag");
            if("msg" in ret){
                dalrt(ret['msg'])
            }
            $(".visitas.key"+flagkey).addClass("typef")
        }
    });
}
function pop(){
    if (ispopajax)return;
    ispopajax=true;
    $.ajax({
        dataType:'json',
        url:'yourls-api.php?t='+now+'&format=json&action=popular&limit=20',
        success:function(tpops){
            ispopajax=false;
            now=tpops['n'];
            if(tpops!=null){
                pops=tpops['r'];
                up()
            }
        }
    });
}
function updateSince()
{
    $(".since").each(function(){

        diff = now-$(this).attr("date");
        if (diff<0) diff=1;

        if (diff>=31536000)
            text="hace "+Math.floor(diff/31536000)+" año"+(diff>=63072000?"s":"");
        else if (diff>=2592000)
            text="hace "+Math.floor(diff/2592000)+" mes"+(diff>=5184000?"es":"");
        else if (diff>=86400)
            text="hace "+Math.floor(diff/86400)+" día"+(diff>=172800?"s":"");
        else if (diff>=3600)
            text="hace "+Math.floor(diff/3600)+" hora"+(diff>=7200?"s":"");
        else if (diff>=60)
            text="hace "+Math.floor((diff/60)%60)+" minuto"+(diff>=120?"s":"");

        $(this).text(text);
    });
}
function up(){
    htmlp="";
    for(i=0;i<pops.length;i++){
        su="http://cos.as/"+pops[i]['k'];
        $(".visitas.key"+pops[i]['k']+" span").html(pops[i]['w']);
        htmlp+="<div class='item'><div class='itemdata'><a target='_blank' title='"+pops[i]['u']+"' href='"+pops[i]['k']+"'><img src='"+pops[i]['i']+"'/>&nbsp;<span>"+pops[i]['t']+"</span></a><span class='since' date='"+pops[i]['d']+"'></span> <span class='act'> <a class='tw' href='http://twitter.com/intent/tweet?text="+su+"'><span class='icon'></span></a> <a class='fb' href='http://www.facebook.com/share.php?u="+su+"'><span class='icon'></span></a></span></div><div class='visitas key"+pops[i]['k']+" chars"+pops[i]['w'].length+pops[i]['y']+"'><span>"+pops[i]['w']+"</span><a class='handup' title='Me gusta' onclick='vote(\""+pops[i]['k']+"\",1)'></a><a class='stats' title='Seguir' target='_blank' href='"+pops[i]['k']+"+"+(pops[i]['n']>1?'all':'')+"'></a><img/><a class='handdown' title='No me gusta' onclick='vote(\""+pops[i]['k']+"\",2)'></a><a class='flag' title='Marcar como inapropiado' onclick='flag(\""+pops[i]['k']+"\")'></a></div></div>";

    }
    dpop.html(htmlp);
    updateSince();

}
function ul(where){
    htmll="";
    for(i=0;i<lasts.length;i++){
        su="http://cos.as/"+lasts[i]['k'];
        htmll+="<div class='item'><div class='itemdata'><a target='_blank' title='"+lasts[i]['u']+"' href='"+lasts[i]['k']+"'><img src='"+lasts[i]['i']+"'/>&nbsp;<span>"+lasts[i]['t']+"</span></a><span class='since' date='"+lasts[i]['d']+"'></span> <span class='act'> <a class='tw' href='http://twitter.com/intent/tweet?text="+su+"'><span class='icon'></span></a> <a class='fb' href='http://www.facebook.com/share.php?u="+su+"'><span class='icon'></span></a></span></div><div class='visitas key"+lasts[i]['k']+" chars"+lasts[i]['w'].length+lasts[i]['y']+"'><span>"+lasts[i]['w']+"</span><a class='handup' title='Me gusta' onclick='vote(\""+lasts[i]['k']+"\",1)'></a><a class='stats' title='Seguir' target='_blank' href='"+lasts[i]['k']+"+"+(lasts[i]['n']>1?'all':'')+"'></a><img/><a class='handdown' title='No me gusta' onclick='vote(\""+lasts[i]['k']+"\",2)'></a><a class='flag' title='Marcar como inapropiado' onclick='flag(\""+lasts[i]['k']+"\")'></a></div></div>";
    }
    if(where>=0)dlast.prepend(htmll);else dlast.append(htmll);
    updateSince();
}
function ih(){
    dwe=$("#we");
    dyou=$("#you");
    dflag=$("#flag");
    dalert=$("#alert");
    dalertc=$("#alertc");
    dalertm=$("#alertm");
    dferrores=$("#ferrores");
    duerrores=$("#uerrores");
    dumode=$('#umode');
    if(dumode)usermode(umode);
    dwerrores=$("#werrores");
    dwmode=$('#wmode');
    if(dwmode)wemode(wmode);
    if(!drd) {
        drd=$("<div id='drd'></div>");
        $('body').append(drd);
        drd.click(ndlg);
    }
    }
function dlg(layer){
    if(rdt)clearTimeout(rdt);
    ddlg=layer;
    drd.addClass("block");
    ddlg.addClass("block");
    ddlg.css("margin-top",$(document).scrollTop());
    }
function ndlg(){
    drd.removeClass("block");
    if(ddlg)ddlg.removeClass("block");
    if(arguments[0]===true){
        if(fok!=null)fok()
    }else{
        if(fnok!=null)fnok()
    }
    fok=fnok=null
}
function usermode(nmode){
    cusermode=nmode;
    duerrores.html("");
    if(dumode)sc(dumode,nmode)
}
function usersend(nmode){
    if(typeof(nmode)!="undefined")cusermode=nmode;
    if(cusermode!="logout")fd=$('#user').serialize();else fd=null;
    $.ajax({
        url: 'yourls-api.php?t='+(new Date()).getTime()+'&format=json&action=user&mode='+cusermode,
        type: "POST",
        data: fd,
        dataType:'json',
        success: function(ret){
            if(ret!=null&&ret['errors']){
                duerrores.html("<ul><li>"+ret['errors'].join("</li><li>")+"</li></ul>");
                return;
            }
            duerrores.html("");
            ndlg();
            if("user" in ret){
                $("#youtext").html(ret["user"]);umode="profile";
            }else{
                $("#youtext").html("Tú");
                umode='login';
            }
            if("msg" in ret){
                dalrt(ret['msg']);
            }
            $.ajax({
                url: 'includes/you.php',
                dataType:'html',
                success: function(h){
                    $('#youc').html(h);
                    updateSince();
                    ih()}
            });
        }
    });
}
function wemode(nmode){
    cwemode=nmode;
    dwerrores.html("");
    if(dwmode)sc(dwmode,nmode)
}
function freset(f){
    $(f).each (function(){this.reset()});
}
function wesend(nmode){
    if(typeof(nmode)!="undefined")cwemode=nmode;
    fd=$('#fcont').serialize();

    $.ajax({
        url:'yourls-api.php?format=json&action=we&mode='+cwemode,
        data:fd,
        dataType:'json',
        type:'POST',
        success:function(ret){
            if(ret!=null&&ret['errors']){
                dwerrores.html("<ul><li>"+ret['errors'].join("</li><li>")+"</li></ul>");
                return
            }
            dwerrores.html("");
            freset("#fcont");
            ndlg();
            if("msg" in ret) dalrt(ret['msg'])
        }
    });
}
function i2(su){
    lstat=$("#lstat_lines");
    if(lstat)on=lstat.attr('startopt');
    if(window.location.hash)chits(window.location.hash.substr(1));
    if(!su)return;
    clip=new ZeroClipboard.Client();
    clip.setHandCursor(true);
    clip.glue('cp');
    clip.setText(su)
}
function dalrt(msg){
    dalertc.html(msg);
    if(arguments.length>1){
        fok=arguments[1];
        fnok=arguments[2];
        sc(dalertm,"prompt");
    }else{
        sc(dalertm,"");
    }
    dlg(dalert);
}

var ZeroClipboard={
    version:"1.0.7",
    clients:{},
    moviePath:'js/ZeroClipboard.swf',
    nextId:1,
    $:function(thingy){
        if(typeof(thingy)=='string')thingy=document.getElementById(thingy);
        if(!thingy.addClass){
            thingy.hide=function(){
                this.style.display='none'
                };

            thingy.show=function(){
                this.style.display=''
                };

            thingy.addClass=function(name){
                this.removeClass(name);
                this.className+=' '+name
                };

            thingy.removeClass=function(name){
                var classes=this.className.split(/\s+/);
                var idx=-1;
                for(var k=0;k<classes.length;k++){
                    if(classes[k]==name){
                        idx=k;
                        k=classes.length
                        }
                    }
                if(idx>-1){
                classes.splice(idx,1);
                this.className=classes.join(' ')
                }
                return this
            };

        thingy.hasClass=function(name){
            return!!this.className.match(new RegExp("\\s*"+name+"\\s*"))
            }
        }
    return thingy
},
setMoviePath:function(path){
    this.moviePath=path
    },
dispatch:function(id,eventName,args){
    var client=this.clients[id];
    if(client){
        client.receiveEvent(eventName,args)
        }
    },
register:function(id,client){
    this.clients[id]=client
    },
getDOMObjectPosition:function(obj,stopObj){
    var info={
        left:0,
        top:0,
        width:obj.width?obj.width:obj.offsetWidth,
        height:obj.height?obj.height:obj.offsetHeight
        };
    while(obj&&(obj!=stopObj)){
        info.left+=obj.offsetLeft;
        info.top+=obj.offsetTop;
        obj=obj.offsetParent
        }
        return info
    },
Client:function(elem){
    this.handlers={};

    this.id=ZeroClipboard.nextId++;
    this.movieId='ZeroClipboardMovie_'+this.id;
    ZeroClipboard.register(this.id,this);
    if(elem)this.glue(elem)
        }
    };

ZeroClipboard.Client.prototype={
    id:0,
    ready:false,
    movie:null,
    clipText:'',
    handCursorEnabled:true,
    cssEffects:true,
    handlers:null,
    glue:function(elem,appendElem,stylesToAdd){
        this.domElement=ZeroClipboard.$(elem);
        var zIndex=37;
        if(this.domElement.style.zIndex){
            zIndex=parseInt(this.domElement.style.zIndex,10)+1
            }
            if(typeof(appendElem)=='string'){
            appendElem=ZeroClipboard.$(appendElem)
            }else if(typeof(appendElem)=='undefined'){
            appendElem=document.getElementsByTagName('body')[0]
            }
            var box=ZeroClipboard.getDOMObjectPosition(this.domElement,appendElem);
        this.div=document.createElement('div');
        var style=this.div.style;
        style.position='absolute';
        style.left=''+box.left+'px';
        style.top=''+box.top+'px';
        style.width=''+box.width+'px';
        style.height=''+box.height+'px';
        style.zIndex=zIndex;
        if(typeof(stylesToAdd)=='object'){
            for(addedStyle in stylesToAdd){
                style[addedStyle]=stylesToAdd[addedStyle]
                }
            }
            appendElem.appendChild(this.div);
    this.div.innerHTML=this.getHTML(box.width,box.height)
    },
getHTML:function(width,height){
    var html='';
    var flashvars='id='+this.id+'&width='+width+'&height='+height;
    if(navigator.userAgent.match(/MSIE/)){
        var protocol=location.href.match(/^https/i)?'https://':'http://';
        html+='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'
        }else{
        html+='<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'
        }
        return html
    },
hide:function(){
    if(this.div){
        this.div.style.left='-2000px'
        }
    },
show:function(){
    this.reposition()
    },
destroy:function(){
    if(this.domElement&&this.div){
        this.hide();
        this.div.innerHTML='';
        var body=document.getElementsByTagName('body')[0];
        try{
            body.removeChild(this.div)
            }catch(e){}
        this.domElement=null;
        this.div=null
        }
    },
reposition:function(elem){
    if(elem){
        this.domElement=ZeroClipboard.$(elem);
        if(!this.domElement)this.hide()
            }
            if(this.domElement&&this.div){
        var box=ZeroClipboard.getDOMObjectPosition(this.domElement);
        var style=this.div.style;
        style.left=''+box.left+'px';
        style.top=''+box.top+'px'
        }
    },
setText:function(newText){
    this.clipText=newText;
    if(this.ready)this.movie.setText(newText)
        },
addEventListener:function(eventName,func){
    eventName=eventName.toString().toLowerCase().replace(/^on/,'');
    if(!this.handlers[eventName])this.handlers[eventName]=[];
    this.handlers[eventName].push(func)
    },
setHandCursor:function(enabled){
    this.handCursorEnabled=enabled;
    if(this.ready)this.movie.setHandCursor(enabled)
        },
setCSSEffects:function(enabled){
    this.cssEffects=!!enabled
    },
receiveEvent:function(eventName,args){
    eventName=eventName.toString().toLowerCase().replace(/^on/,'');
    switch(eventName){
        case'load':
            this.movie=document.getElementById(this.movieId);
            if(!this.movie){
            var self=this;
            setTimeout(function(){
                self.receiveEvent('load',null)
                },1);
            return
        }
        if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){
            var self=this;
            setTimeout(function(){
                self.receiveEvent('load',null)
                },100);
            this.ready=true;
            return
        }
        this.ready=true;
        this.movie.setText(this.clipText);
            this.movie.setHandCursor(this.handCursorEnabled);
            break;
        case'mouseover':
            if(this.domElement&&this.cssEffects){
            this.domElement.addClass('hover');
            if(this.recoverActive)this.domElement.addClass('active')
                }
                break;
        case'mouseout':
            if(this.domElement&&this.cssEffects){
            this.recoverActive=false;
            if(this.domElement.hasClass('active')){
                this.domElement.removeClass('active');
                this.recoverActive=true
                }
                this.domElement.removeClass('hover')
            }
            break;
        case'mousedown':
            if(this.domElement&&this.cssEffects){
            this.domElement.addClass('active')
            }
            break;
        case'mouseup':
            if(this.domElement&&this.cssEffects){
            this.domElement.removeClass('active');
            this.recoverActive=false
            }
            break
        }
        if(this.handlers[eventName]){
        for(var idx=0,len=this.handlers[eventName].length;idx<len;idx++){
            var func=this.handlers[eventName][idx];
            if(typeof(func)=='function'){
                func(this,args)
                }else if((typeof(func)=='object')&&(func.length==2)){
                func[0][func[1]](this,args)
                }else if(typeof(func)=='string'){
                window[func](this,args)
                }
            }
        }
}
}